<template>
    <div class="edu-page-warp">
        <el-card shadow="never" body-style="padding: 24px 24px 6px 24px;">
            
            <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="90px">
                <el-row>
                    <el-col :span="18">
                        <div class="float-left">
                            <div class="edu-page-title">{{ $t('common.text.filterCondition') }}</div>
                        </div>
                    </el-col>
                    <el-col :span="6" class="float-right" style="text-align:right">
                        <el-button @click="reset">{{ $t('common.btn.reset') }}</el-button>
                        <el-button type="primary" @click="onSubmit">{{ $t('common.btn.filter') }}</el-button>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                    <el-col :span="8">
                        <el-form-item label="年级:" prop="year">
                            <el-date-picker
                                v-model="queryForm.year"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="培养层次:" prop="trainingLevel">
                            <el-select v-model="queryForm.trainingLevel" style="width: 100%">
                                <el-option
                                    v-for="item in options.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                            <el-form-item label="类别:" prop="professionCateGory">
                                <el-select
                                    v-model="queryForm.professionCateGory"
                                    style="width: 100%;"
                                >
                                    <el-option
                                        v-for="item in options.professionCateGory"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="发布状态:" prop="status">
                            <el-select v-model="queryForm.status" style="width: 100%;" clearable>
                                <el-option
                                    v-for="item in options.pushStatus"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        
        <el-card v-loading="loading" shadow="never" body-style="padding: 24px;">
            <el-row>
                <div class="edu-page-title mg-top">{{ $t('culture.template.index') }}</div>
            </el-row>
            
            <el-row style="padding:15px 0 15px 0;">
                <div class="float-left">
                    <!-- <el-input
                        v-model="queryForm.name"
                        :placeholder="$t('common.pla.pleaseInput')"
                        style="width:250px"
                        @keyup.enter.native="filter"
                    >
                        <i
                            slot="suffix"
                            class="el-icon-search"
                            style="margin-top:10px;cursor:pointer"
                            @click="filter"
                        ></i>
                    </el-input> -->
                    <el-input
                        v-model="queryForm.name"
                        placeholder="请输入培养方案模板名称搜索"
                        style="width:250px"
                        @keyup.enter.native="filter"
                    >
                        <i
                            slot="suffix"
                            class="el-icon-search"
                            style="margin-top:10px;cursor:pointer"
                            @click="filter"
                        ></i>
                    </el-input>
                </div>
                <div class="float-right">
                    <el-button @click="pushTemplate">{{ $t('common.btn.publish') }}</el-button>
                    <el-button @click="copy">复制</el-button>
                    <el-button @click="showDeleteTemplateDialog">{{ $t('common.btn.delete') }}</el-button>
                    <el-button type="primary" @click="createTemplate">{{ $t('common.btn.add') }}</el-button>
                </div>
            </el-row>
            <!--table -->
            <el-table :data="templates" stripe size="mini" @selection-change="chooseTemplate" tooltip-effect="light" :default-sort = "{prop: 'status', order: 'descending'}">
                <el-table-column type="selection" width="50" />
                <el-table-column prop="id" label="序号" width="100" />
                <el-table-column label="模板名称" prop="name" show-overflow-tooltip>
                    <template slot-scope="scope" >
                        <span>
                            <el-button
                                type="text"
                                @click="preview(scope.row)"
                            >{{ scope.row.name }}</el-button>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="年级" width="100" prop="year" sortable>
                    <template slot-scope="props">{{ props.row.year }}</template>
                </el-table-column>
                <el-table-column label="培养层次" width="100">
                    <template slot-scope="props">{{ props.row.trainingLevelI18n}}</template>
                </el-table-column>
                    <el-table-column label="类别" width="100">
                        <template
                            slot-scope="scope"
                        >{{ scope.row.professionCateGory=="1"? "专业大类": "专业" }}</template>
                    </el-table-column>
                <el-table-column label="发布状态" width="100" :sortable="true" :sort-method="sortByDate">
                    <!-- <template slot-scope="props">
                        <el-tag
                            :type="props.row.status === 1 ? 'info' : 'success'"
                            size="mini"
                            disable-transitions
                        >{{ getPushLable(props.row.status) }}</el-tag>
                    </template> -->
                     <template slot-scope="props">
                        <el-tag
                            v-if="props.row.status === 1"
                            type="info"
                            size="mini"
                            disable-transitions
                        >草稿</el-tag>
                        <el-tag
                            v-if="props.row.status === 2"
                            type="success"
                            size="mini"
                            disable-transitions
                        >已发布</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.status === 1"
                            type="text"
                            size="mini"
                            @click="edit(scope.row)"
                        >编辑</el-button>
                        <el-button
                            v-if="scope.row.status === 1"
                            type="text"
                            size="mini"
                            @click="remove(scope.row)"
                        >删除</el-button>
                        <el-button
                            v-if="scope.row.status === 2"
                            type="text"
                            size="mini"
                            @click="revert(scope.row)"
                        >撤销</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col>
                    <el-pagination
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20, 40, 80, 100]"
                        :page-size="queryForm.pageSize_"
                        :total="queryForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float:right;margin-top:10px"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </el-col>
            </el-row>
        </el-card>
        <el-dialog
            :visible.sync="copyVisible"
            title="复制培养方案模板"
            width="35%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form ref="year" :model="copyForm" inline>
                <el-form-item
                    :rules="[
            { required: true, message: '请选择年级'}
          ]"
                    label="年级:"
                    prop="year"
                >
                    <el-select v-model="copyForm.year" placeholder="请选择年级" clearable>
                        <el-option
                            v-for="item in options.grade"
                            :key="item.value"
                            :label="item.label + '级'"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="!!copyForm.year">
                    <i class="el-icon-warning"></i>
                    <span>选择年级将会生成该年级新的模板</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetCopy('year')">取 消</el-button>
                <el-button type="primary" @click="copyOk('year')">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { queryDic, findTrainingLevelByProjId } from "common/src/api/dictionary";
import {
    getCultureTemplateList,
    deleteCultureTemplateById,
    pushCultureTemplateById,
    copyCultureTemplate,
    revertCultureTemplateById
} from "common/src/api/culture/bachelor";
import Bus from "common/src/utils/bus";
import UTILS from "common/src/utils/utils";
import mixin from 'common/src/mixins/index';
const DELETE_TYPE = {
    SINGLE: "SINGLE",
    BATCH: "BATCH"
};
export default {
    name: "bcl-culture-template-manage",
    mixins: [mixin],
    data() {
        return {
            loading: false,
            queryForm: {
                status: "",
                projId: "",
                year: "",
                trainingLevel: "",
                name: "",
                formLearning: "",
                professionCateGory: "",
                degreeType: "",
                trainingCategory: "",
                pageNum_: 1,
                pageSize_: 20,
                total: 0
            },
            options: {
                projId: [],
                grade: [],
                trainingLevel: [],
                formLearning: [],
                trainingCategory: [],
                category: [],
                professionCateGory: [
                    { value: "1", label: "专业大类" },
                    { value: "2", label: "专业" }
                ],
                pushStatus: [
                    { label: "草稿", value: 1 },
                    { label: "已发布", value: 2 },
                ],
                degreeType: []
            },
            copyForm: {
                year: "",
                idSet: []
            },
            copyVisible: false,
            chooseTemplates: [],
            templates: [],
            deleteType: "",
            deleteId: ""
        };
    },
    mounted() {
        this.init();
        this.initProjId();
        Bus.$on("updateCurrentManageDeptId", id => {
            this.queryForm.projId = id;
            this.handleChangeProjId();
        });
    },
    created() {
        Bus.$on("selectCultureTemplate", templateId => {
            this.onSubmit();
        });
    },
    beforeDestroy() {
        Bus.$off("selectCultureTemplate");
    },
    methods: {
        sortByDate(obj1, obj2){
            let val1 = obj1.status
            let val2 = obj2.status
            return val1 - val2
        },
        initProjId() {
            let currentUser = this.global.currentUser;
            this.queryForm.projId = currentUser.currentManageDptId;
        },
        init() {
            this.queryForm["x-token"] =
                this.$store.state.session.sessionid ||
                localStorage.getItem("sessionid") ||
                "";
            // 绑定年级
            const now = new Date();
            const currentYear = now.getFullYear()+1;
            const minYear = currentYear - 7;
            for (let year = currentYear+4; year > minYear; year--) {
                const obj = { label: year, value: year };
                this.options.grade.push(obj);
            }
            // 绑定培养层次
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_PYCC", "X_XXXS", "X_GLBM", "X_PYLB", "X_XWLX"]
            };
            // 绑定类别
            this.options.category.push({
                label: this.$t("culture.profession.bigProfession"),
                value: "1"
            });
            this.options.category.push({
                label: this.$t("culture.profession.profession"),
                value: "2"
            });
            queryDic(data).then(res => {
                if (res.code === 200) {
                    UTILS.fillSelect(
                        {
                            formLearning: "X_XXXS",
                            degreeType: "X_XWLX",
                            trainingCategory: "X_PYLB"
                        },
                        res.data,
                        this.options
                    );
                    //this.queryForm.projId = Object.keys(res.data.X_GLBM)[0];
                    for (const key in res.data.X_GLBM) {
                        this.options["projId"].push({
                            value: key,
                            label: res.data.X_GLBM[key]
                        });
                    }
                    this.changeTrainingLevelOptions();
                    this.onSubmit(); // 进入页面，默认筛选
                }
            });
        },
        // reset() {
        //     this.$refs.queryForm.resetFields();
        //     this.changeTrainingLevelOptions();
        //     this.onSubmit();
        // },
        reset() {
            this.$refs.queryForm.resetFields();
            this.changeTrainingLevelOptions();
            this.queryForm.name = "";
            this.onSubmit();
        },
        // 筛选
        onSubmit() {
            this.getTemplateList();
        },
        handleChangeProjId() {
            this.reset();
        },
        changeTrainingLevelOptions() {
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.options[optionKey] = [];
            _.each(dataObj, level => {
                this.options[optionKey].push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        filter() {
            this.onSubmit();
        },
        chooseTemplate(val) {
            this.chooseTemplates = val;
        },
        // 发布培养模板
        pushTemplate() {
            if (this.chooseTemplates.length === 0) {
                this.$message({
                    type: "info",
                    message: "请选择要发布的培养方案模板"
                });
                return;
            }
            this.$confirm("是否发布该培养方案模板?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.deleteType = DELETE_TYPE.BATCH;
                    this.deleteId = "";
                    this.confirmPush();
                })
                .catch(e => {});
        },
        copy() {
            if (this.chooseTemplates.length === 0) {
                this.$message({
                    type: "info",
                    message: "请选择要复制的培养方案模板"
                });
                return;
            }
            this.copyVisible = true;
        },
        copyOk(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.copyForm.idSet = _.map(this.chooseTemplates, "id");
                    copyCultureTemplate(this.copyForm).then(res => {
                        if (res && res.code === 200) {
                            this.copyVisible = false;
                            let message =
                                "由于培养方案模板批量复制每条数据结果差异，可前往公共导出页面查看批量复制培方案模板情况表格详情。";
                            this.$alert(message, "批量复制结果").then(res => {
                                this.onSubmit();
                                this.chooseTemplates.length = 0;
                                this.$refs[formName].resetFields();
                            });
                        }
                    });
                }
            });
        },
        resetCopy(formName) {
            this.copyVisible = false;
            this.$refs[formName].resetFields();
        },
        // 显示批量删除对话框
        showDeleteTemplateDialog() {
            if (this.chooseTemplates.length === 0) {
                this.$message({
                    type: "info",
                    message: "请选择要删除的培养方案模板"
                });
                return;
            }
            this.$confirm("是否删除该培养方案模板?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.deleteType = DELETE_TYPE.BATCH;
                    this.deleteId = "";
                    this.confirmDelete();
                })
                .catch(e => {});
        },
        // 创建模板
        createTemplate() {
            if (this.queryForm.projId) {
                this.$router.push({
                    path: "/bclCultureTemplateDetail/" + this.queryForm.projId
                });
            }
        },
        // 预览模板
        preview(row) {
            let routerName = "/bclCultureTemplateView";
            this.$router.push({
                path: routerName,
                query: {
                    projId: this.queryForm.projId,
                    id: row.id,
                    dataType: 1,
                    schoolTerms: row.schoolTerm
                }
            });
        },
        // 编辑模板
        edit(row) {
            this.$router.push({
                name: "bclCultureTemplateDetail",
                params: {
                    projId: this.queryForm.projId,
                    id: row.id,
                    schoolTerms: row.schoolTerm
                }
            });
        },
        // 显示单个删除对话框
        remove(row) {
            this.$confirm("是否删除该培养方案模板?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.deleteType = DELETE_TYPE.SINGLE;
                    this.deleteId = row.id;
                    this.confirmDelete();
                })
                .catch(e => {});
        },
        // 撤销
        revert(row) {
            this.$confirm("是否撤销该培养方案模板?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.confirmRevert(row.id);
                })
                .catch(e => {});
        },
        // 处理分页大小
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getTemplateList();
        },
        // 处理分页改变
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val;
            this.getTemplateList(false);
        },
        // 获取模板列表
        getTemplateList(pageNumReset = true) {
            if (pageNumReset) {
                this.queryForm.pageNum_ = 1;
            }
            getCultureTemplateList(this.queryForm).then(response => {
                if (response.code === 200) {
                    this.templates = response.data.list;
                    this.queryForm.total = response.data.total_;
                }
            });
        },
        // 确认删除
        confirmDelete() {
            let ids = null;
            if (this.deleteType === DELETE_TYPE.SINGLE) {
                ids = [this.deleteId];
            } else {
                ids = this.chooseTemplates.map(c => c.id);
            }
            deleteCultureTemplateById(ids).then(response => {
                if (response.code === 200) {
                    if(response.data){
                        this.$confirm("序号为"+response.data+"的培养模版已被引用，删除失败", "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning"
                        })
                        .then(() => {
                            this.onSubmit();
                        })
                    }else{
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                        this.onSubmit();
                    }
                    
                }
            });
        },
        // 确认发布
        confirmPush() {
            let ids = null;
            let status = 1;
            if (this.deleteType === DELETE_TYPE.SINGLE) {
                ids = [this.deleteId];
            } else {
                ids = this.chooseTemplates.map(c => c.id);
                //status = this.chooseTemplates.map(c => c.status != 1);
                this.chooseTemplates.forEach(c =>{
                    if(c.status != 1){
                        status = 2
                    }
                })
                console.log(status)

            }
            if(status == 1){
                pushCultureTemplateById(ids).then(response => {
                    if (response.code === 200) {
                        this.$message({
                            type: "success",
                            message: "发布成功"
                        });
                        this.onSubmit();
                    }
                });
            }else{
                this.$message({
                        type: "warning",
                        message: "模板已发布，不能重复发布"
                    });
            }
            
        },
        // 确认撤销
        confirmRevert(id) {
            revertCultureTemplateById(id).then(response => {
                let { code } = response;
                if (code === 200) {
                    this.$message({
                        type: "success",
                        message: "撤销成功"
                    });
                    this.onSubmit();
                }
            });
        },
        // getTrainLevelLabel(value) {
        //     if (this.options.trainingLevel.find(t => t.value === value)) {
        //         return this.options.trainingLevel.find(t => t.value === value)
        //             .label;
        //     } else {
        //         return value;
        //     }
        // },
        getFormLearningLabel(value) {
            if (this.options.formLearning.find(t => t.value === value)) {
                return this.options.formLearning.find(t => t.value === value)
                    .label;
            } else {
                return value;
            }
        },
        getPushLable(value) {
            const pushStatu = this.options.pushStatus.find(
                t => t.value === value
            );
            if (pushStatu === "{}") {
                return value;
            } else {
                return pushStatu.label;
            }
        }
    }
};
</script>
